<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Helpers\Database;
use App\Helpers\Date;
use App\Helpers\Password;
use App\Models\UserModel;

class UserRepository
{
    public function __construct(private UserModel $userModel = new UserModel) {}

    /**
     * Consulta el id de un usuario desde el valor de una columna.
     */
    public function findIdByColumn(string $column, mixed $value): ?string
    {
        return $this->userModel->reset()
            ->select('id')
            ->where($column, $value)
            ->value('id');
    }

    /**
     * Registra la información de un usuario.
     */
    public function insert(array $data): string
    {
        $id = Database::generateUuid();

        $data = array_merge($data, [
            'id' => $id,
            'password' => Password::encrypt($data['password']),
            'is_active' => $data['is_active'] ?? true,
            'created_at' => Date::getCurrentDatetime(),
            'updated_at' => Date::getCurrentDatetime(),
        ]);

        $this->userModel->reset()->insert($data);

        return $id;
    }

    /**
     * Modifica la información de un usuario.
     */
    public function update(string $id, array $data): void
    {
        if (isset($data['password'])) {
            $data['password'] = Password::encrypt($data['password']);
        }

        $data['updated_at'] = Date::getCurrentDatetime();

        $this->userModel->reset()
            ->where('id', $id)
            ->update($data);
    }
}
